package github._3y.concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Auther DRevelation
 * @Date 2020-05-27 下午 15:32
 * @Desc
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        //CyclicBarrier允许一组线程互相等待，直到到达某个公共屏障点。如果改成3，因为下面只有2个线程，会阻塞
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                String name = Thread.currentThread().getName();
                if (name.equals("Thread-0")) {
                    name = "3y";
                } else {
                    name = "女朋友";
                }

                System.out.println("【" + name + "】到了体育西");

                try {
                    cyclicBarrier.await();
                    System.out.println("跟【" + name + "】去夜上海吃东西~");

                    cyclicBarrier.await();
                    System.out.println("【" + name + "】洗澡");

                    cyclicBarrier.await();
                    System.out.println("一起聊天");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
